package cn.iocoder.yudao.module.pmp.controller.admin.project;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.crm.controller.admin.business.vo.business.CrmBusinessRespVO;
import cn.iocoder.yudao.module.crm.controller.admin.business.vo.business.CrmBusinessTransferReqVO;
import cn.iocoder.yudao.module.crm.dal.dataobject.business.CrmBusinessProductDO;
import cn.iocoder.yudao.module.crm.dal.dataobject.product.CrmProductDO;
import cn.iocoder.yudao.module.crm.service.business.CrmBusinessService;
import cn.iocoder.yudao.module.crm.service.customer.CrmCustomerService;
import cn.iocoder.yudao.module.crm.service.product.CrmProductService;
import cn.iocoder.yudao.module.pmp.controller.admin.project.vo.ProjectPageReqVO;
import cn.iocoder.yudao.module.pmp.controller.admin.project.vo.ProjectRespVO;
import cn.iocoder.yudao.module.pmp.controller.admin.project.vo.ProjectSaveReqVO;
import cn.iocoder.yudao.module.pmp.dal.dataobject.project.ProjectDO;
import cn.iocoder.yudao.module.pmp.service.project.ProjectService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import com.mzt.logapi.starter.annotation.LogRecord;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.crm.enums.LogRecordConstants.*;

/**
 * 项目登记
 */
@Tag(name = "管理后台 - 项目登记")
@RestController
@RequestMapping("/pmp/project")
@Validated
public class ProjectController {

    @Resource
    private ProjectService projectService;
    @Resource
    private CrmBusinessService businessService;
    @Resource
    private CrmProductService productService;
    @Resource
    private CrmCustomerService customerService;

    @Resource
    private AdminUserApi adminUserApi;

    @PostMapping("/create")
    @Operation(summary = "创建项目登记")
    public CommonResult<Long> createProject(@Valid @RequestBody ProjectSaveReqVO createReqVO) {
        return success(projectService.createProject(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新项目登记")
    public CommonResult<Boolean> updateProject(@Valid @RequestBody ProjectSaveReqVO updateReqVO) {
        projectService.updateProject(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除项目登记")
    @Parameter(name = "id", description = "编号", required = true)
    public CommonResult<Boolean> deleteProject(@RequestParam("id") Long id) {
        projectService.deleteProject(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得项目登记")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<ProjectRespVO> getProject(@RequestParam("id") Long id) {
        ProjectDO project = projectService.getProject(id);
        Long businessId = project.getBusinessId();
        ProjectRespVO projectRespVO = null;
        try {
            // 拼接产品项
            List<CrmBusinessProductDO> businessProducts = businessService.getBusinessProductListByBusinessId(businessId);
            Map<Long, CrmProductDO> productMap = productService.getProductMap(
                    convertSet(businessProducts, CrmBusinessProductDO::getProductId));
            List<CrmBusinessRespVO.Product> list = BeanUtils.toBean(businessProducts, CrmBusinessRespVO.Product.class, businessProductVO ->
                    MapUtils.findAndThen(productMap, businessProductVO.getProductId(),
                            product -> businessProductVO.setProductName(product.getName())
                                    .setProductNo(product.getNo()).setProductUnit(product.getUnit())));
            projectRespVO = BeanUtils.toBean(project, ProjectRespVO.class);
            projectRespVO.setProducts(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return success(projectRespVO);
    }


    @GetMapping("/page")
    @Operation(summary = "获得项目登记分页")
    public CommonResult<PageResult<ProjectRespVO>> getProjectPage(@Valid ProjectPageReqVO pageReqVO) {
        PageResult<ProjectDO> pageResult = projectService.getProjectPage(pageReqVO, getLoginUserId());
        return success(BeanUtils.toBean(pageResult, ProjectRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出项目登记 Excel")
    @ApiAccessLog(operateType = EXPORT)
    public void exportProjectExcel(@Valid ProjectPageReqVO pageReqVO,
                                   HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ProjectDO> list = projectService.getProjectPage(pageReqVO, getLoginUserId()).getList();
        // 导出 Excel
        ExcelUtils.write(response, "项目登记.xls", "数据", ProjectRespVO.class,
                BeanUtils.toBean(list, ProjectRespVO.class));
    }

    @PutMapping("/transfer")
    @Operation(summary = "项目转移")
    public CommonResult<Boolean> transferBusiness(@Valid @RequestBody CrmBusinessTransferReqVO reqVO) {
        projectService.transferProject(reqVO, getLoginUserId());
        return success(true);
    }

}
